package leetcode.medium.groupAnagrams;

import java.util.*;

/**
 * Solution
 * <a href="https://leetcode.cn/problems/group-anagrams/description/?envType=study-plan-v2&envId=top-100-liked">49. 字母异位词分组</a>
 *
 * @since 2024/9/1
 */
public class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        // 初始化 单词 -> 真实单词列表 的映射
        Map<String, List<String>> resultMap = new HashMap<>();
        for (String word : strs) {
            String sorted = toSortedStr(word);
            resultMap.computeIfAbsent(sorted, k -> new ArrayList<>());
            resultMap.get(sorted).add(word);
            int a = 0;
        }
        // 打包结果
        return new ArrayList<>(resultMap.values());
    }

    private String toSortedStr(String original) {
        char[] charArray = original.toCharArray();
        Arrays.sort(charArray);
        return new String(charArray);
    }
}